package com.gss.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gss.common.core.service.BaseServiceImpl;
import com.gss.datasource.mapper.sys.SysDeptRoleMapper;
import com.gss.datasource.mapper.sys.SysUserDeptMapper;
import com.gss.entity.R;
import com.gss.entity.enums.ConstantEnum;
import com.gss.entity.sys.dto.SysDept;
import com.gss.entity.sys.dto.SysDeptRole;
import com.gss.entity.sys.dto.SysUserDept;
import com.gss.entity.sys.vo.SysDeptRoleVo;
import com.gss.entity.sys.vo.SysRoleMenuVo;
import com.gss.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author DYang
 * @date 2023/6/17
 */
@Service("sysDeptService")
public class ISysDeptServiceImpl extends BaseServiceImpl<SysDept> implements ISysDeptService {

    @Autowired
    private SysDeptRoleMapper deptRoleMapper;
    @Autowired
    private SysUserDeptMapper userDeptMapper;

    @Transactional
    @Override
    public R<String> oauthRole(SysDeptRoleVo entity) {
        Integer deptId = entity.getId();
        List<SysRoleMenuVo> roleList = entity.getRoleList();
        if (deptId == null || CollUtil.isEmpty(roleList)) {
            return R.error(ConstantEnum.PARAM_ERROR);
        }

        for (SysRoleMenuVo menuVo : roleList) {
            SysDeptRole deptRole = new SysDeptRole();
            deptRole.setDeptId(deptId);
            deptRole.setRoleId(menuVo.getId());
            deptRole.setEnable(0);
            deptRole.setCreateTime(new Date());

            deptRoleMapper.insert(deptRole);
        }

        return R.ok("授权成功");
    }

    @Transactional
    @Override
    public R<String> deleteRole(List<Integer> idList) {
        QueryWrapper<SysUserDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("dept_role_id",idList);
        Long count = userDeptMapper.selectCount(queryWrapper);
        if (count != null && count > 0) {
            return R.error(ConstantEnum.USING_ERROR);
        }

        int batch = deptRoleMapper.deleteBatchIds(idList);
        return batch > 0 ? R.ok("删除成功") : R.error(ConstantEnum.DEL_ERROR);
    }
}
